package com.itheima.线程安全.Synchronized;

public class Demo {
    public static void main(String[] args) {
        MyRunnable mr = new MyRunnable();

        Thread t1 = new Thread(mr);
        Thread t2 = new Thread(mr);

        t1.setName("窗口一");
        t2.setName("窗口二");

        t1.start();
        t2.start();
    }
}
class MyRunnable implements Runnable{
    private static int ticketCount=40;

    @Override
    public void run() {
        while (true){
            if ("窗口一".equals(Thread.currentThread().getName())){
                //同步方法
              boolean result=synchronizedMthod();
              if (result){
                  break;
              }
            }

            if ("窗口二".equals(Thread.currentThread().getName())){
                //同步代码块
                synchronized (this){
                    if (ticketCount==0){
                        break;
                    }else {
                        try {
                            Thread.sleep(200);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        ticketCount--;
                        System.out.println(Thread.currentThread().getName()+"在卖票，还剩下"+ticketCount+"张票");
                    }
                }
            }
        }
    }

    //同步方法锁对象：this
    //同步静态方法锁对象：当前类的类名.class，当前类的字节码文件对象

    private synchronized boolean synchronizedMthod() {
        if (ticketCount==0){
            return true;
        }else {
            try{
                Thread.sleep(10);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            ticketCount--;
            System.out.println(Thread.currentThread().getName()+"在卖票，还剩下"+ticketCount+"张票");
            return false;
        }
    }
}